//
//  RwdtabBar.swift
//  Weibo_rwd
//
//  Created by 任文迪 on 16/7/9.
//  Copyright © 2016年 spaceX. All rights reserved.
//

import UIKit

class RwdtabBar: UITabBar {
    
    //  点击点击撰写按钮的闭包
    var composeButtonClosure: (()->())?
    //懒加载的方式在tabbar上面创建一个button
    lazy var addButton: UIButton = {
        //创建一个button
        let button = UIButton()
        //设置button 的backgroundImage 和 image 
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        //设置高亮状态的图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        //设置背景高亮图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        //button自适应大小
        button.sizeToFit()
        //添加点击事件
        button.addTarget(self, action: "clickAction", forControlEvents: .TouchUpInside)
        //设置图片缩进
//        button.imageEdgeInsets = UIEdgeInsetsMake(5,0,-5,0)
        
        return button
        
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(addButton)
        
    }
    // 加载xib或者storyboard才会调用
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //按钮点击事件
    func clickAction() {
        
        print("点击了加号")
        
        //传递这个闭包
        composeButtonClosure?()
        
    }
    
    
    
    //重写layoutsubviews方法
    override func layoutSubviews() {
        
        super.layoutSubviews()
        //设置addbutton的frame
        addButton.center.x = frame.width / 2
        
        addButton.center.y = frame.height / 2
        //设置一个计数器
        var index = 0
        //设置每个子控件的宽度
        let subViewWidth = self.frame.size.width / 5
        //遍历tabbar所有的子控件
        for value in subviews {
            
            if value .isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                value.frame.origin.x = CGFloat(index) * subViewWidth
                value.frame.size.width = subViewWidth
                
                if index == 1 {
                    
                    index++
                    
                }
                
                index++
                
            }
            
        }
        
    }
    
    

}
